#!/usr/bin/perl
use CGI;
use CGI qw/:standard/;
use CGI::Pretty qw/:standard *-table *-div/;
use FindBin '$Bin';
use lib $Bin;
use DBI;
use Data::Dumper;
use CgiUtil;

my $g_task_id;
my $g_ex = 0;
my %g_table;

sub get_detail_data {
	my $content = "";
	my $db_name = "d_stock";
	my $db_host = "localhost";
	my $db_user = "root";
	my $db_pwd = "123456";
	my $dbh = DBI->connect("dbi:mysql:$db_name:$db_host", $db_user, $db_pwd);

        my $sql = "select d.c_date,d.c_operate,d.c_code,n.c_name,d.c_price,d.c_rate,d.c_volume,d.c_earn,d.c_reason from t_task_detail as d right join t_stock_names_A as n on d.c_code=n.c_code  where d.c_task_id=$g_task_id order by d.c_date asc,d.c_operate desc";
        my $rows = $dbh->selectall_arrayref($sql);
	my $cnt = 0;
	foreach (@$rows) {
		my ($date,$operate,$code,$name,$price,$rate,$volume,$earn,$reason) = @$_;
		$cnt ++;
		$g_table{"$cnt"}{"date"} = $date;
		$g_table{"$cnt"}{"operate"} = $operate eq "buy" ? "买入" : "卖出";
		$g_table{"$cnt"}{"code"} = $code;
		$g_table{"$cnt"}{"name"} = $name;
		$g_table{"$cnt"}{"price"} = $price;
		$g_table{"$cnt"}{"rate"} = $rate;
		$g_table{"$cnt"}{"volume"} = $volume;
		$g_table{"$cnt"}{"earn"} = sprintf("%.2f",$earn);
		$g_table{"$cnt"}{"reason"} = $reason;
	}
#	print Dumper(\%g_table);
	if ($g_ex == 1) {
		$content .= '<table border="1"><tr><th>日期</th><th>操作</th><th>代码</th><th>名称</th><th>价格</th><th>收益率</th><th>股数</th><th>收益</th><th>明细</th></tr>';
		foreach my $key (sort {$a<=>$b} keys %g_table) {
			$content .= "<tr><td>$g_table{$key}{'date'}</td>" 
				. "<td>$g_table{$key}{'operate'}</td>" 
				. "<td><a href=\"http://stock.quote.stockstar.com/realtime_$g_table{$key}{'code'}.shtml\" target=\"_blank\">$g_table{$key}{'code'}</a></td>" 
				. "<td>$g_table{$key}{'name'}</td>"
				. "<td>$g_table{$key}{'price'}</td>" 
				. "<td>$g_table{$key}{'rate'}</td>" 
				. "<td>$g_table{$key}{'volume'}</td>" 
				. "<td>$g_table{$key}{'earn'}</td>" 
				. "<td>$g_table{$key}{'reason'}</td></tr>";
		}
	} else {
		$content .= '<table border="1"><tr><th>日期</th><th>操作</th><th>代码</th><th>名称</th><th>价格</th><th>收益率</th><th>股数</th><th>收益</th></tr>';
		foreach my $key (sort {$a<=>$b} keys %g_table) {
			$content .= "<tr><td>$g_table{$key}{'date'}</td>" 
				. "<td>$g_table{$key}{'operate'}</td>" 
				. "<td><a href=\"http://stock.quote.stockstar.com/realtime_$g_table{$key}{'code'}.shtml\" target=\"_blank\">$g_table{$key}{'code'}</a></td>" 
				. "<td>$g_table{$key}{'name'}</td>"
				. "<td>$g_table{$key}{'price'}</td>"
				. "<td>$g_table{$key}{'rate'}</td>" 
				. "<td>$g_table{$key}{'volume'}</td>" 
				. "<td>$g_table{$key}{'earn'}</td>" 
				. "</tr>";
		}
	}
	return $content;
}

sub main {
	print myhead("操作明细");
	print h3('操作明细');

	$g_task_id = url_param('task_id');
	$g_ex = url_param('ex');
	if (!defined($g_task_id)) {
		print h3("任务编号不正确");
	} else {
		print h3("任务编号:$g_task_id");
		print get_detail_data($g_task_id);
	}
}

main();
